<template>
  <div class="editor">
    <quill-editor :style="{height} " v-model="editorData" ref="myQuillEditor" :options="editorOption"></quill-editor>
  </div>
</template>

<script>

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { Quill, quillEditor } from 'vue-quill-editor'
import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module'
import { UPLOAD_URL } from '@/infra/conf/default'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
import { AppVersion } from '@/framework/constant/Common'

Quill.register('modules/ImageExtend', ImageExtend)

export default {
  name: 'RichEditor',
  components: {
    quillEditor
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: String,
      default: '200px'
    },
    placeholder: {
      type: String,
      default: '在这里输入内容'
    }
  },
  watch: {
    value() {
      this.editorData = this.value
    },
    editorData() {
      this.$emit('input', this.editorData)
    }
  },
  data() {
    return {
      editorData: this.value,
      editorOption: {
        placeholder: this.placeholder,
        modules: {
          ImageExtend: {
            loading: true,
            name: 'file',
            action: UPLOAD_URL,
            headers: (xhr) => {
              xhr.setRequestHeader('Authorization', getToken())
              xhr.setRequestHeader('token', getToken())
              xhr.setRequestHeader('AppVersion', AppVersion)
              return xhr
            },
            response: (res) => {
              if (res.code === 2001) {
                removeToken()
                router.replace('/login')
                return
              }
              return res.data
            }
          },
          toolbar: {
            container,
            handlers: {
              image: function() {
                QuillWatch.emit(this.quill.id)
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.editor {
  line-height: 1;
  margin-bottom: 70px;
}
</style>
